#!/usr/bin/env python
# -*-coding:utf-8-*-
# @Time : 2021/9/22 10:33
# @Author : Li Yan
import os
import shutil

import ffmpeg

from utils.logo_tool import shrink_img


def water2video(video: str, logo: str, height: int) -> object:
    shrink_img(logo, height, 10)
    water = ffmpeg.input(logo)
    return ffmpeg.filter([video, water], 'overlay', 10, 10).filter_('scale', 720, height)


def video2mp4(lock: object, video: str, logo: str) -> None:
    lock.acquire()
    if video.rsplit('.', 1)[1] in ['mp4', 'MP4', 'Mp4', 'mP4']:
        shutil.move(video, video.rsplit('.', 1)[0] + '.flv')
        video = video.rsplit('.', 1)[0] + '.flv'

    probe = ffmpeg.probe(video)
    video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
    width = int(video_stream['width'])
    height = int(video_stream['height'])
    new_hight = int(height * 720 / width)

    if new_hight % 2 != 0:
        new_hight += 1
    raw_video = ffmpeg.input(video)
    audio = raw_video.audio
    if logo:
        s_video = water2video(raw_video.video, logo, new_hight)
    else:
        s_video = raw_video.video.filter_('scale', 720, new_hight)

    mp4_file = video.rsplit('.', 1)[0] + '.mp4'
    out = ffmpeg.output(audio, s_video, mp4_file, **{'qscale:v': 5, 'qscale:a': 5, 'r': 25}).overwrite_output()
    ffmpeg.run(out)

    if logo:
        os.remove(logo)
    os.remove(video)
    lock.release()
